package com.csoa.community.activity;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.message.BasicNameValuePair;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.AsyncTask;
import android.os.IBinder;
import android.text.Html;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.csoa.community.R;
import com.csoa.community.bean.AttachBean;
import com.csoa.community.bean.EmailBean;
import com.csoa.community.net.WcfAsyncTask;
import com.csoa.community.requests.AbstractRequest;
import com.csoa.community.requests.ComWordRequest;
import com.csoa.community.requests.EmailDetailRequest;
import com.csoa.community.requests.EmailDownAttachRequest;
import com.csoa.community.requests.EmailReadStateRequest;
import com.csoa.community.requests.OffDocDownLoadAttachRequest;
import com.csoa.community.services.DownLoadAttachService;
import com.csoa.community.services.UpgradeService;
import com.csoa.community.singletons.GlobalVars;
import com.csoa.community.utils.AndroidUtils;
import com.csoa.community.utils.StringUtils;
import com.csoa.community.widget.CommonDialog;
import com.csoa.community.widget.PullToRefreshBase.OnRefreshListener;
import com.csoa.community.widget.PullToRefreshScrollView;

public class EmailDetailActivity extends BaseActivity {

	private Button mOffDetailBtn;
	private LinearLayout mOffDetailLayout;
	private TextView mOffDetailFromCodeTV;
	private TextView mOffDetailCreateDateTV;
	private TextView mOffDetailFromTV;
	private TextView mOffDetailTitleTV;
	private TextView mOffDetailContentTV;
	private TextView mOffDetailAttachTV;
	private LinearLayout mOffDetailAttendMeetingLayout;
	private String RID;
	// private String mMessageID;
	private LinearLayout mOffDetailAttachLayout;
	// 判断是否是签批(如果点击签批按钮 issued = true，否则是false)
	private boolean issued;
	private LinearLayout mOffDetailAttachTotalLayout;
	private Button mEmailPreBtn;
	private Button mEmailNextBtn;

	// 收件人姓名
	protected String mDisName;
	protected String mGUID;
	private int mIsAddMetting = 0;
	private boolean isupdate;
	private String readType;
	protected boolean isRefreshComWord;
	private CommonDialog caculatorDialog;
	private boolean isMeeting;
	protected DownLoadAttachService service;
	private RelativeLayout mOffDetailSubmitLayout;
	private Button mEmailReadStateBtn;
	// protected boolean isHaveReadState = true;
	private boolean isFromRead;
	private int mPosition;
	private EmailBean mEmailBean;
	private AsyncTask<AbstractRequest, Object, AbstractRequest> task;
	private PullToRefreshScrollView mPullemailDetailScroll;
	private ScrollView emailDetailScroll;
	// 检测看有没有标记为未读状态的list
	private ArrayList<Boolean> listIsHaveReadState;
	private LayoutInflater inflater;
	private View mScollerContentView;
	public static final int AddresseeRequestCode = 3;

	private static Map<String, EmailBean> contents;

	@Override
	public void initUI() {
		setContentView(R.layout.ui_email_detail);
		inflater = LayoutInflater.from(this);
		mPullemailDetailScroll = (PullToRefreshScrollView) this
				.findViewById(R.id.emailDetailScroll);
		mPullemailDetailScroll.setMode(PullToRefreshScrollView.MODE_PULL_DOWN_TO_REFRESH);
		mPullemailDetailScroll.setOnRefreshListener(new OnRefreshListener() {

			@Override
			public void onRefresh() {
				buildRequestDetail(mEmailBean.MessageID, RID);
			}
			
		});
		emailDetailScroll = mPullemailDetailScroll.refreshableView;
		mScollerContentView = inflater.inflate(R.layout.ui_email_detail_scroller, null);
		emailDetailScroll.addView(mScollerContentView);
		// 详细按钮
		mOffDetailBtn = (Button) this.findViewById(R.id.offDetailBtn);

		mEmailReadStateBtn = (Button) this.findViewById(R.id.emailReadStateBtn);
		mOffDetailLayout = (LinearLayout) this
				.findViewById(R.id.offDetailLayout);
		mOffDetailFromCodeTV = (TextView) this
				.findViewById(R.id.offDetailFromCodeTV);
		mOffDetailCreateDateTV = (TextView) this
				.findViewById(R.id.offDetailCreateDateTV);

		mOffDetailFromTV = (TextView) this.findViewById(R.id.offDetailFromTV);
		// 标题
		mOffDetailTitleTV = (TextView) this.findViewById(R.id.offDetailTitleTV);
		// 内容
		mOffDetailContentTV = (TextView) this
				.findViewById(R.id.offDetailContentTV);
		// 附件
		mOffDetailAttachTV = (TextView) this
				.findViewById(R.id.offDetailAttachTV);
		// 详情按钮点击
		mOffDetailBtn.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if (mOffDetailLayout.getVisibility() == View.VISIBLE) {
					mOffDetailLayout.setVisibility(View.GONE);
					mOffDetailBtn.setText("详细");
				} else {
					mOffDetailLayout.setVisibility(View.VISIBLE);
					mOffDetailBtn.setText("隐藏");
				}
			}
		});

		mEmailPreBtn = (Button) this.findViewById(R.id.offDetailSubmitBtn);
		mEmailPreBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (mPosition == 0) {
					showToast("没有更多邮件了");
					return;
				}
				stopTask();
				mScollerContentView.setVisibility(View.INVISIBLE);
				mOffDetailAttachLayout.removeAllViews();
				mEmailReadStateBtn.setOnClickListener(null);
				if (!isFromRead) {
					mEmailBean = EmailActivity.mToBeReadEmails
							.get(mPosition - 1);
				} else {
					mEmailBean = EmailActivity.mHaveReadEmails
							.get(mPosition - 1);
				}
				mPosition--;
				if (contents.containsKey(mEmailBean.MessageID)) {
					mEmailBean = contents.get(mEmailBean.MessageID);
					setDataToView(mEmailBean);
				} else {
					buildRequestDetail(mEmailBean.MessageID, RID);
				}
				emailDetailScroll.scrollTo(0, 0);

			}
		});

		mEmailNextBtn = (Button) this.findViewById(R.id.offDetailCancelBtn);
		mEmailNextBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				if (!isFromRead) {
					if (mPosition == EmailActivity.mToBeReadEmails.size() - 1) {
						showToast("没有更多邮件了");
						return;
					}

				} else if (mPosition == EmailActivity.mHaveReadEmails.size() - 1) {
					showToast("没有更多邮件了");
					return;
				}

				stopTask();
				mScollerContentView.setVisibility(View.INVISIBLE);
				mOffDetailAttachLayout.removeAllViews();
				mEmailReadStateBtn.setOnClickListener(null);
				if (!isFromRead) {
					mEmailBean = EmailActivity.mToBeReadEmails
							.get(mPosition + 1);
				} else {
					mEmailBean = EmailActivity.mHaveReadEmails
							.get(mPosition + 1);
				}
				mPosition++;
				if (contents.containsKey(mEmailBean.MessageID)) {
					mEmailBean = contents.get(mEmailBean.MessageID);
					setDataToView(mEmailBean);
				} else {
					buildRequestDetail(mEmailBean.MessageID, RID);
				}
				emailDetailScroll.scrollTo(0, 0);
			}
		});

		// 提交按钮layout
		mOffDetailSubmitLayout = (RelativeLayout) this
				.findViewById(R.id.offDetailSubmitLayout);

		// 附件layout（包括附件的标题）
		mOffDetailAttachTotalLayout = (LinearLayout) this
				.findViewById(R.id.offDetailAttachTotalLayout);
		// mOffDetailAttachTotalLayout
		// .setOnClickListener(new View.OnClickListener() {
		//
		// @Override
		// public void onClick(View v) {
		// buildAttachRequest(mEmailBean.MessageID, "机关大院临时搬迁的通知.doc",
		// ".doc");
		// }
		// });

		// 附件layout
		mOffDetailAttachLayout = (LinearLayout) this
				.findViewById(R.id.offDetailAttachLayout);

	}

	// /**
	// * 待阅公文提交
	// *
	// * @param comWord
	// * 常用语
	// * @param addressee
	// * 收件人
	// * @param aUsername
	// * 登录名
	// * @param IsAddMetting
	// * 是否参加会议
	// */
	// private void submit(String comWord, String addressee, String aUsername,
	// int IsAddMetting) {
	// showProgress();
	// List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
	// params.add(new BasicNameValuePair("LogName", aUsername));
	// params.add(new BasicNameValuePair("RID", RID));
	// params.add(new BasicNameValuePair("Content", comWord));
	// params.add(new BasicNameValuePair("UserGuid", mGUID));
	// params.add(new BasicNameValuePair("UserDisName", addressee));
	// params.add(new BasicNameValuePair("IsAddMetting", IsAddMetting + ""));
	//
	// OffDocDetailSubmitRequest detailSubmitRequest = new
	// OffDocDetailSubmitRequest(
	// readType, params);
	//
	// new WcfAsyncTask(this, new OnUICallback() {
	//
	// @Override
	// public void onGetResult(AbstractRequest request) {
	// dismisProgress();
	// OffDocDetailSubmitRequest detailCallBackRequest =
	// (OffDocDetailSubmitRequest) request;
	// if (detailCallBackRequest.success != null
	// && !"0".equals(detailCallBackRequest.success)) {
	// EmailDetailActivity.this.showToast("提交成功");
	// EmailDetailActivity.this.setResult(RESULT_OK);
	// finish();
	// } else {
	// EmailDetailActivity.this.showToast("提交失败");
	// }
	//
	// }
	//
	// @Override
	// public void onCancel() {
	// dismisProgress();
	// }
	//
	// @Override
	// public void onProgress(int progress, String msg) {
	// dismisProgress();
	// EmailDetailActivity.this.showToast(msg);
	// }
	// }).execute(detailSubmitRequest);
	//
	// }

	/**
	 * 联网标记未读已读
	 * 
	 * @param aReadStateRequest
	 */
	protected void netRequestUpdateReadState(
			EmailReadStateRequest aReadStateRequest) {
		showProgress();
		new WcfAsyncTask(this, new OnUICallback() {

			@Override
			public void onGetResult(AbstractRequest request) {
				dismisProgress();
				EmailReadStateRequest readStateRequest = (EmailReadStateRequest) request;
				String success = readStateRequest.success;
				if (!StringUtils.isEmpty(success) && !"0".equals(success)) {
					if (mEmailBean.isHaveReadState) {
						mEmailBean.isHaveReadState = false;
						mEmailReadStateBtn.setText("已读");
					} else {
						mEmailBean.isHaveReadState = true;
						mEmailReadStateBtn.setText("未读");
					}

				} else {
					EmailDetailActivity.this.showToast("未读状态更新失败");
				}

			}

			@Override
			public void onCancel() {
				dismisProgress();
			}

			@Override
			public void onProgress(int progress, String msg) {
				dismisProgress();
				EmailDetailActivity.this.showToast(msg);
			}
		}).execute(aReadStateRequest);
	}

	/**
	 * 根据是否是快速签发，显示或隐藏部分view
	 * 
	 * @param visibility
	 */
	public void showOrHiddenToBeRead(int visibility) {
		mOffDetailBtn.setVisibility(visibility);
		mOffDetailTitleTV.setVisibility(visibility);
		mOffDetailContentTV.setVisibility(visibility);
		// mOffDetailAttachTotalLayout.setVisibility(visibility);
	}

	@Override
	public void initData() {

		contents = new HashMap<String, EmailBean>();
		listIsHaveReadState = new ArrayList<Boolean>();
		mEmailBean = (EmailBean) getIntent().getSerializableExtra("emailBean");
		mPosition = this.getIntent().getIntExtra("position", 0);
		// isupdate = this.getIntent().getBooleanExtra(GlobalVars.ISUPDATE,
		// false);
		isFromRead = this.getIntent().getBooleanExtra("isRead", false);
		// if(!isFromRead) {
		// isHaveReadState = true;
		// }

		if (!contents.containsKey(mEmailBean.MessageID)) {
			buildRequestDetail(mEmailBean.MessageID, RID);
		} else {
			mEmailBean = contents.get(mEmailBean.MessageID);
			setDataToView(mEmailBean);
		}

	}

	/**
	 * 获取详情页数据（构建详情页数据Request）
	 * 
	 * @param request
	 */
	protected void buildRequestDetail(String ID, String RID) {
//		showProgress();
		mPullemailDetailScroll.showHeadView();
		List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
		params.add(new BasicNameValuePair("uid",
				GlobalVars.currentUser.loginName));
		params.add(new BasicNameValuePair("MessageID", ID));
		netRequestDetail(new EmailDetailRequest(params));
	}

	/**
	 * 获取详情页数据
	 * 
	 * @param request
	 */
	private void netRequestDetail(AbstractRequest request) {
		stopTask();
		task = new WcfAsyncTask(this, new OnUICallback() {

			@Override
			public void onGetResult(AbstractRequest request) {
				dismisProgress();
				mPullemailDetailScroll.onRefreshComplete();
				EmailDetailRequest detailRequest = (EmailDetailRequest) request;
				if (detailRequest.emailBean != null) {
					contents.remove(mEmailBean.MessageID);
					contents.put(mEmailBean.MessageID, detailRequest.emailBean);
					mEmailBean = detailRequest.emailBean;
					setDataToView(detailRequest.emailBean);
					// 不是签发就请求附件
					// if (!issued) {
					// buildAttachRequest(RID);
					// }
				}
			}

			@Override
			public void onCancel() {
				mPullemailDetailScroll.onRefreshComplete();
				dismisProgress();
			}

			@Override
			public void onProgress(int progress, String msg) {
				dismisProgress();
				EmailDetailActivity.this.showToast(msg);
			}
		});

		task.execute(request);
	}

	private void stopTask() {
		if (task != null) {
			task.cancel(true);
		}
	}

	/**
	 * 下载附件构建Request
	 * 
	 * @param request
	 */
	protected void buildAttachRequest(String aMessageID, AttachBean attach) {
		showProgress();
		List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
		params.add(new BasicNameValuePair("MessageID", aMessageID));
		params.add(new BasicNameValuePair("uid",
				GlobalVars.currentUser.loginName));
		params.add(new BasicNameValuePair("filename", attach.FileName));
		params.add(new BasicNameValuePair("filetype", attach.FileExtend));
		netRequestAttach(new EmailDownAttachRequest(params), attach);
	}

	/**
	 * 下载附件
	 * 
	 * @param request
	 */
	private void netRequestAttach(EmailDownAttachRequest request,
			final AttachBean attach) {
		new WcfAsyncTask(this, new OnUICallback() {

			@Override
			public void onGetResult(AbstractRequest request) {
				dismisProgress();
				EmailDownAttachRequest attachRequest = (EmailDownAttachRequest) request;
				if (!StringUtils.isEmpty(attachRequest.success)
						&& "1".equals(attachRequest.success)) {

					EmailDetailActivity.this
							.showToast("附件后台下载中...,下载完成自动存入CSOA目录中");
					startService(attach);
				} else {
					EmailDetailActivity.this.showToast("获取附件失败,附件可能已经删除");
				}
			}

			@Override
			public void onCancel() {
				dismisProgress();
			}

			@Override
			public void onProgress(int progress, String msg) {
				EmailDetailActivity.this.showToast(msg);
			}
		}).execute(request);
	}

	/**
	 * 附件下载完毕之后显示在界面中
	 * 
	 * @param mAttachs
	 */
	protected void setDataToAttachView(List<AttachBean> mAttachs) {

		if (mAttachs == null || mAttachs.size() == 0) {
			mOffDetailAttachTotalLayout.setVisibility(View.GONE);
			return;
		}
		mOffDetailAttachTotalLayout.setVisibility(View.VISIBLE);
		mOffDetailAttachLayout.removeAllViews();
		for (int i = 0; i < mAttachs.size(); i++) {
			final AttachBean attach = mAttachs.get(i);
			TextView text = new TextView(this);
			text.setText("附件" + (i + 1) + ":" + attach.FileName);
			text.setTextSize(18);
			text.setTextColor(this.getResources().getColor(R.color.attach));
			text.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					boolean isAttachExists = GlobalVars.getInst().isAttachExists(EmailDetailActivity.this, attach.FileName);
					
					if(!isAttachExists) {
						
						if (!AndroidUtils
								.isNetworkValidate(EmailDetailActivity.this)) {
							EmailDetailActivity.this.showToast("无法检测到网络,检查网络是否开启");
							return;
						}
						buildAttachRequest(mEmailBean.MessageID, attach);
					}

				}
			});
			mOffDetailAttachLayout.addView(text);
		}
	}

	private void startService(AttachBean attach) {

		Intent intent = new Intent();
		intent.setClass(this, UpgradeService.class);
		intent.putExtra("AttachID", mEmailBean.MessageID);
		intent.putExtra("FileName", attach.FileName);
		intent.putExtra("FileExtend", attach.FileExtend);
		intent.putExtra("fromemail", "fromemail");
		this.startService(intent);
	}

	private ServiceConnection connection = new ServiceConnection() {

		@Override
		public void onServiceDisconnected(ComponentName name) {
			service = null;
		}

		@Override
		public void onServiceConnected(ComponentName name, IBinder ibinder) {
			service = ((DownLoadAttachService.DownLoadBinder) ibinder)
					.getService();
		}
	};

	protected void buildDownLoadAttachRequest(AttachBean attach) {
		showProgress();
		List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
		params.add(new BasicNameValuePair("RID", RID));
		params.add(new BasicNameValuePair("MessageID", attach.Id));
		params.add(new BasicNameValuePair("FileType", attach.FileType));
		netRequestDownAttach(new OffDocDownLoadAttachRequest(params), attach);
	}

	private void netRequestDownAttach(OffDocDownLoadAttachRequest request,
			final AttachBean attach) {

		new WcfAsyncTask(this, new OnUICallback() {

			@Override
			public void onGetResult(AbstractRequest request) {
				dismisProgress();
				OffDocDownLoadAttachRequest downAttachRequest = (OffDocDownLoadAttachRequest) request;
				if (!StringUtils.isEmpty(downAttachRequest.success)
						&& "1".equals(downAttachRequest.success)) {

					EmailDetailActivity.this
							.showToast("附件后台下载中...,下载完成自动存入CSOA目录中");
					startService(attach);
				} else {
					EmailDetailActivity.this.showToast("获取附件失败,附件可能已经删除");
				}
			}

			@Override
			public void onCancel() {
				dismisProgress();
			}

			@Override
			public void onProgress(int progress, String msg) {
				dismisProgress();
				EmailDetailActivity.this.showToast(msg);
			}
		}).execute(request);

	}

	/**
	 * 详情页view的数据展示
	 * 
	 * @param aEmailBean
	 */
	protected void setDataToView(final EmailBean aEmailBean) {
		// mOffDetailLayout =
		// (LinearLayout)this.findViewById(R.id.offDetailLayout);
		mPullemailDetailScroll.onRefreshComplete();
		mEmailReadStateBtn.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
				if (aEmailBean.isHaveReadState) {
					params.clear();
					params.add(new BasicNameValuePair("MessageID",
							mEmailBean.MessageID));
					params.add(new BasicNameValuePair("Flag", 0 + ""));
				} else {
					params.clear();
					params.add(new BasicNameValuePair("MessageID",
							mEmailBean.MessageID));
					params.add(new BasicNameValuePair("Flag", 1 + ""));
				}
				netRequestUpdateReadState(new EmailReadStateRequest(params));
			}
		});

		if (mEmailBean.isHaveReadState) {
			mEmailReadStateBtn.setText("未读");
		} else {
			mEmailReadStateBtn.setText("已读");
		}

		mScollerContentView.setVisibility(View.VISIBLE);
		mOffDetailFromCodeTV.setText("标题:" + aEmailBean.Subject);
		mOffDetailCreateDateTV.setText("日期:" + aEmailBean.Date);
		mOffDetailFromTV.setText("抄送:" + Html.fromHtml(aEmailBean.SentTo));

		mOffDetailTitleTV.setText("发件人:  " + Html.fromHtml(aEmailBean.Sender));
		mOffDetailContentTV.setText("正文:  "
				+ Html.fromHtml(aEmailBean.BodyHtml));
		setDataToAttachView(aEmailBean.Attachments);
		// mOffDetailAttachTV.setText("");

	}

	/**
	 * 获取常用语(构建Request)
	 * 
	 * @param aLogName
	 */
	protected void buildComRequest(String aLogName) {
		if (isRefreshComWord) {
			showProgress();
		}
		List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
		params.add(new BasicNameValuePair("LogName", aLogName));
		netRequestCom(new ComWordRequest(this, params));
	}

	/**
	 * 获取常用语
	 * 
	 * @param request
	 */
	private void netRequestCom(ComWordRequest request) {
		new WcfAsyncTask(this, new OnUICallback() {

			@Override
			public void onGetResult(AbstractRequest request) {
				dismisProgress();
				ComWordRequest comWordRequest = (ComWordRequest) request;
				if (comWordRequest.mComWords != null) {
					if (comWordRequest.mComWords.size() == 0) {
						EmailDetailActivity.this.showToast("暂无常用语信息");
						return;
					}
					// showDialog(comWordRequest.mComWords);
				}
			}

			@Override
			public void onCancel() {
				isRefreshComWord = false;
				dismisProgress();
			}

			@Override
			public void onProgress(int progress, String msg) {
				EmailDetailActivity.this.showToast(msg);
			}
		}).execute(request);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode,
			Intent intent) {
		if (resultCode == RESULT_OK) {
			// String name = intent.getStringExtra("name");
			// mGUID = intent.getStringExtra("id");
		}
	}

	@Override
	public boolean onKeyDown(int paramInt, KeyEvent paramKeyEvent) {

		// contents
		boolean isHaveReadState = true;
		Intent intent = new Intent();
		if (isFromRead) {
			for (String MessageId : contents.keySet()) {
				isHaveReadState = contents.get(MessageId).isHaveReadState;
				if (!isHaveReadState) {
					break;
				}
			}

		} else {
			for (String MessageId : contents.keySet()) {
				isHaveReadState = contents.get(MessageId).isHaveReadState;
				if (isHaveReadState) {
					break;
				}
			}

		}

		intent.putExtra("isHaveReadState", isHaveReadState);
		setResult(RESULT_OK, intent);
		finish();
		return super.onKeyDown(paramInt, paramKeyEvent);
	}
}
